import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_shop/model/category.dart';
import 'package:flutter_shop/model/categoryGoodsList.dart';
import 'package:flutter_shop/service/service_method.dart';
import 'package:provide/provide.dart';

import 'category_goods_list.dart';
import 'child_category.dart';

class LeftCategoryNavProvide with ChangeNotifier {
  int clickIndex = -1;
  var categoryNavList = [];
  var categoryGoodsList = [];
  var childList; //大类的子类所有赋值
  var categoryId; //点击项的categoryId

  //设置当前点击的Index
  setClickIndex(int clickIndex, context) async {
    if (this.clickIndex != clickIndex) {
      //设置当前点击项
      this.clickIndex = clickIndex;
      await getCategory();
      await getGoodsList(categoryId: categoryId);

      Provide.value<ChildCategory>(context)
          .setChildCategory(childList, categoryId);

      Provide.value<CategoryGoodsListProvide>(context)
          .setGoodsList(categoryGoodsList);

      notifyListeners();
    }
  }

  getCategory() async {
    await request('getCategory').then((val) {
      var data = json.decode(val.toString());
      CategoryModel category = CategoryModel.fromJson(data);
      categoryNavList = category.data;
      childList = categoryNavList[clickIndex].bxMallSubDto; //大类的子类所有赋值
      categoryId =
          categoryNavList[clickIndex].mallCategoryId; //获取点击项的categoryId
    });
  }

  getGoodsList({String categoryId}) async {
    var data = {
      'categoryId': categoryId == null ? '4' : categoryId,
      'categorySubId': '',
      'page': 1,
    };
    await request('getMallGoods', fromData: data).then((val) {
      var data = json.decode(val.toString());
      CategoryGoodsListModel goodsList = CategoryGoodsListModel.fromJson(data);
      categoryGoodsList = goodsList.data;
    });
  }
}
